
package org.movee.spring.data.hugegraph.repository.query;


import org.movee.spring.data.hugegraph.gremlin.GremlinTraversal;
import org.movee.spring.data.hugegraph.query.HugeOperations;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.IncorrectResultSizeDataAccessException;

import java.util.List;

public interface HugeQueryExecution {
    Object execute(GremlinTraversal query, Class<?> type);

    @RequiredArgsConstructor
    final class CollectionExecution implements HugeQueryExecution {

        @NonNull
        private final HugeOperations operations;

        @Override
        public Object execute(@NonNull GremlinTraversal traversal, @NonNull Class<?> returnedActualType) {
            return operations.traversal(traversal, returnedActualType);
        }
    }


    @RequiredArgsConstructor
    final class SingleEntityExecution implements HugeQueryExecution {

        @NonNull
        private final HugeOperations operations;
        private final boolean limiting;

        @Override
        @SuppressWarnings("unchecked")
        public Object execute(@NonNull GremlinTraversal traversal, @NonNull Class<?> returnedActualType) {

            List<Object> objects = operations.traversal(traversal, returnedActualType);

            if (objects.isEmpty()) {
                return null;
            }

            if (objects.size() == 1 || limiting) {
                return objects.get(0);
            }

            throw new IncorrectResultSizeDataAccessException(1, objects.size());
        }
    }

}
